# coding=utf-8

import base64
import json
import sys
from urllib.request import urlopen
from urllib.request import Request
from urllib.error import URLError
from urllib.parse import urlencode
import pymysql
from downloadimg import *
# 打开数据库连接

conn = pymysql.connect(host="139.9.219.187",port=3306,user="lh",passwd="159753",db="movie_big_data",charset='utf8')
# 使用cursor()方法获取操作游标
cursor = conn.cursor()
# 防止https证书校验不正确
import ssl
ssl._create_default_https_context = ssl._create_unverified_context

API_KEY = 'WAvcyStS2PNM9QoG9S7RfL6u'

SECRET_KEY = 'DvGYuvFaGUYG36uWqoiA4yEMrcz68pot'

OCR_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"

"""  TOKEN start """
TOKEN_URL = 'https://aip.baidubce.com/oauth/2.0/token'

"""
    获取token
"""
def fetch_token():
    params = {'grant_type': 'client_credentials',
              'client_id': API_KEY,
              'client_secret': SECRET_KEY}
    post_data = urlencode(params)
    post_data = post_data.encode('utf-8')
    req = Request(TOKEN_URL, post_data)
    try:
        f = urlopen(req, timeout=5)
        result_str = f.read()
    except URLError as err:
        print(err)
    result_str = result_str.decode()
    result = json.loads(result_str)
    if ('access_token' in result.keys() and 'scope' in result.keys()):
        if not 'brain_all_scope' in result['scope'].split(' '):
            print ('please ensure has check the  ability')
            exit()
        return result['access_token']
    else:
        print ('please overwrite the correct API_KEY and SECRET_KEY')
        exit()

"""
    读取文件
"""
def read_file(image_path):
    f = None
    try:
        f = open(image_path, 'rb')
        return f.read()
    except:
        print('read image file fail')
        return None
    finally:
        if f:
            f.close()

"""
    调用远程服务
"""
def request(url, data):
    req = Request(url, data.encode('utf-8'))
    has_error = False
    try:
        f = urlopen(req)
        result_str = f.read()
        result_str = result_str.decode()
        return result_str
    except  URLError as err:
        print(err)

if __name__ == '__main__':
    # 获取access token
    downloadimg()
    token = fetch_token()
    # 拼接通用文字识别高精度url
    image_url = OCR_URL + "?access_token=" + token
    text = ""
    # 读取测试图片
    file_content = read_file('1.jpg')
    # 调用文字识别服务
    result = request(image_url, urlencode({'image': base64.b64encode(file_content)}))
    # 解析返回结果
    result_json = json.loads(result)
    newresult=result_json["words_result"]
    new_result=[]
    newresult=newresult[7:]
    for index in range(len(newresult)):
        if index%5==0:
             temp_result = (newresult[index]["words"],newresult[index+1]["words"],newresult[index+2]["words"],newresult[index+3]["words"],newresult[index+4]["words"])
             new_result.append(temp_result)
    try:
        list_douban_detail =new_result
        for index in list_douban_detail:
            # print("%"+index[1]+"%",index[2])
            sql = "update echarts_map_box_office set box_office = '%s',shows= '%s',numbers='%s' where province_name like '%s'" % (
            index[2], index[3], index[4], '%' + index[1] + '%')
            try:
                cursor.execute(sql)
                conn.commit()
                print("数据更新成功")
            except Exception as e:
                conn.rollback()
                print("数据库更新失败")
        # cursor.executemany(sql_movie_detail,list_douban_detail)
        # conn.commit()
    except Exception as e:
        print(e)
        conn.rollback()
    # 关闭
    finally:
        conn.close()
        cursor.close()
